import request from "@/service/axios/index";
import OSS from "ali-oss";

let ossClient = null;
// 初始化 OSS 客户端单例
function getOSSClient(config) {
    if (!ossClient) {
        ossClient = new OSS(config);
    } else {
        // 如果需要更新配置，可以考虑重新实例化客户端
        // 或者检查哪些配置可以动态更新而无需重新实例化
        console.warn('OSS client already exists. If you need to update the configuration, consider re-instantiating the client.');
    }
    return ossClient;
}

// 更新 OSS 客户端配置（重新实例化客户端）
function updateOSSClientConfig(newConfig) {

    ossClient = null; // 销毁旧实例
    ossClient = new OSS({
        region: newConfig.region,
        accessKeyId: newConfig.AccessKeyId,
        accessKeySecret: newConfig.AccessKeySecret,
        stsToken: newConfig.SecurityToken, // 注意这里是 SecurityToken，不是 stsToken
        bucket: newConfig.bucket
    }); // 创建新实例
    // console.log("更新实例：", newConfig)
}
function newConfigFromResponse(responseData) {
    // console.log("要校验新的配置：\n", responseData)
    debugger
    // 假设响应数据包含以下字段：region, accessKeyId, accessKeySecret, stsToken, bucket
    const { region, AccessKeyId, AccessKeySecret, Expiration, bucket } = responseData;
    debugger
    // 验证必要的字段是否存在
    if (!region || !AccessKeyId || !AccessKeySecret || !bucket) {
        throw new Error('Invalid response data: missing required fields.');
    }

    // 返回配置对象
    return {
        region,
        AccessKeyId,
        AccessKeySecret,
        Expiration,
        bucket,
    };
}


//调用接口获取临时上传凭证
async function getSTStoken() {
    try {
        const res = await request.get({ url: '/oss/aliyun/get_sts_token_for_oss_upload' });
        // console.log("临时凭证：\n", res.data)
        updateOSSClientConfig(res.data);
        return res.data;
    } catch (e) {
        console.log("临时凭证获取失败", e);
    }
}



// / 上传文件并监听进度
async function uploadFileWithProgress(file, prefix) {
    try {

        const config = await getSTStoken();
        // console.log("临时凭证config：\n", config)
        // console.log("临时凭证配置：\n", config)
        const client = getOSSClient(config);

        const result = await client.put(`${prefix}${file.name}`, file, {
            progress: (p) => {
                console.log(`上传进度: ${Math.floor(p * 100)}%`);
            },
        });

        // console.log('上传成功:', result);
    } catch (error) {
        // console.error('上传失败:', error);
    }
}






export {
    getOSSClient,
    getSTStoken,
    updateOSSClientConfig,
    uploadFileWithProgress
}


